// src/pages/UserList/components/UserModal.tsx
import { addUser, editUser } from '@/services/user';
import { useModel } from '@umijs/max';
import { DatePicker, Form, Input, Modal, Select, message } from 'antd';
import dayjs from 'dayjs';
import React, { useEffect, useState } from 'react';

const { Option } = Select;

type UserModalProps = {
  visible: boolean;
  isEdit: boolean;
  disableSubmit: boolean;
  currentUserId: string;
  currentUser?: any; // 当前用户数据
  onOk: (values: any) => void;
  onCancel: () => void;
  checkUsername: (data: {
    tableName: string;
    fieldName: string;
    fieldVal: string;
    dataId?: string;
  }) => Promise<any>;
  checkPhone: (data: {
    tableName: string;
    fieldName: string;
    fieldVal: string;
    dataId?: string;
  }) => Promise<any>;
  checkEmail: (data: {
    tableName: string;
    fieldName: string;
    fieldVal: string;
    dataId?: string;
  }) => Promise<any>;
};

const UserModal: React.FC<UserModalProps> = ({
  visible,
  isEdit,
  disableSubmit,
  currentUserId,
  currentUser,
  onOk,
  onCancel,
}) => {
  const [form] = Form.useForm();
  const [confirmLoading, setConfirmLoading] = useState(false);
  const { initialState } = useModel('@@initialState');
  const companyId = initialState?.currentUser?.companyId;
  useEffect(() => {
    if (visible && isEdit && currentUser) {
      // 编辑时直接使用当前行数据
      const userData = { ...currentUser };
      // 处理日期字段
      if (userData.birthday) {
        userData.birthday = dayjs(userData.birthday);
      }
      form.setFieldsValue(userData);
    } else if (visible && !isEdit) {
      // 新增时重置表单
      form.resetFields();
    }
  }, [visible, isEdit, currentUser, form]);

  const handleOk = async () => {
    try {
      const values = await form.validateFields();
      setConfirmLoading(true);

      // 处理日期字段
      const submitData = { ...values };
      if (submitData.birthday) {
        submitData.birthday = submitData.birthday.format('YYYY-MM-DD');
      }

      let response;
      if (isEdit && currentUserId) {
        // 编辑
        response = await editUser({ ...submitData, id: currentUserId });
      } else {
        // 新增
        response = await addUser({
          ...submitData,
          companyId: companyId,
        });
      }

      if (response.code === 200) {
        message.success(isEdit ? '编辑成功' : '新增成功');
        onOk(submitData);
      } else {
        message.error(isEdit ? '编辑失败' : '新增失败');
      }
    } catch (error) {
      console.error('提交表单失败:', error);
      // message.error('表单验证失败或提交出错');
    } finally {
      setConfirmLoading(false);
    }
  };

  const validatePhone = async (_: any, value: string) => {
    if (!value) {
      return Promise.resolve(); // 手机号非必填
    }
    if (!/^1[3|4|5|7|8][0-9]\d{8}$/.test(value)) {
      return Promise.reject(new Error('请输入正确格式的手机号码!'));
    }
    return Promise.resolve();
  };

  const validateEmail = async (_: any, value: string) => {
    if (!value) {
      return Promise.resolve(); // 邮箱非必填
    }
    // 简单的邮箱校验正则
    if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(value)) {
      return Promise.reject(new Error('请输入正确格式的邮箱地址!'));
    }
    return Promise.resolve();
  };

  return (
    <Modal
      title={isEdit ? '编辑用户' : '新增用户'}
      open={visible}
      onOk={handleOk}
      onCancel={onCancel}
      confirmLoading={confirmLoading}
      maskClosable={false}
      width={600}
    >
      <Form
        form={form}
        layout="vertical"
        disabled={disableSubmit}
        autoComplete="off"
      >
        <Form.Item
          name="realName"
          label="真实姓名"
          rules={[{ required: true, message: '请输入真实姓名!' }]}
        >
          <Input placeholder="请输入真实姓名" />
        </Form.Item>
        <Form.Item
          name="sex"
          label="性别"
          rules={[{ required: true, message: '请选择性别!' }]}
        >
          <Select placeholder="请选择性别">
            <Option value={0}>未知</Option>
            <Option value={1}>男</Option>
            <Option value={2}>女</Option>
          </Select>
        </Form.Item>
        <Form.Item
          name="phone"
          label="手机号码"
          rules={[{ validator: validatePhone }]}
        >
          <Input
            placeholder="请输入手机号码"
            autoComplete="off"
            autoCorrect="off"
            autoCapitalize="off"
            spellCheck="false"
          />
        </Form.Item>
        <Form.Item
          name="email"
          label="邮箱"
          rules={[{ validator: validateEmail }]}
        >
          <Input
            placeholder="请输入邮箱"
            autoComplete="off"
            autoCorrect="off"
            autoCapitalize="off"
            spellCheck="false"
          />
        </Form.Item>

        <Form.Item
          name="birthday"
          label="生日"
          rules={[{ required: true, message: '请选择生日!' }]}
        >
          <DatePicker
            placeholder="请选择生日"
            style={{ width: '100%' }}
            format="YYYY-MM-DD"
          />
        </Form.Item>

        <Form.Item
          name="idCard"
          label="身份证号"
          rules={[
            { required: true, message: '请输入身份证号!' },
            {
              pattern:
                /^[1-9]\d{5}(18|19|20)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/,
              message: '请输入正确的身份证号!',
            },
          ]}
        >
          <Input
            placeholder="请输入身份证号"
            autoComplete="off"
            autoCorrect="off"
            autoCapitalize="off"
            spellCheck="false"
          />
        </Form.Item>

        {!isEdit && (
          <Form.Item
            name="password"
            label="密码"
            rules={[
              { required: true, message: '请输入密码!' },
              { min: 6, message: '密码至少6位!' },
            ]}
          >
            <Input.Password
              placeholder="请输入密码"
              autoComplete="new-password"
              autoCorrect="off"
              autoCapitalize="off"
              spellCheck="false"
            />
          </Form.Item>
        )}
      </Form>
    </Modal>
  );
};

export default UserModal;
